package com.musiklegal;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.Calendar;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore.Audio;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class TrackInfo extends Activity {
	boolean state = false;
	Button play, dl, moreSong;
	MediaPlayer mediaPlayer;
	String address;
	static boolean fromCatalogue;
	static boolean fromFriend =false;
	File file;
	String len = "0";
	HttpURLConnection c;
	ImageView imv;
	public static boolean isCatalogue=false;
	URL url;
	static DataSong ds;
	static SongD item;
	static String mercapi;
	ProgressBar statusBar;
	Handler donlot;
	TextView song, artist, album, genre, label, idring, composer, publisher;
	int stat = 0;
	int size=0,pictsize=200;
	boolean delayed=false;
	boolean tes =false;
	
	public void onResume()
	{
		
		super.onResume();
	}
	
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		
		
		donlot = new Handler();
		setContentView(R.layout.track);
		dl = (Button) this.findViewById(R.id.download);
		statusBar = (ProgressBar) findViewById(R.id.statusDownload);
		play = (Button) this.findViewById(R.id.play);
		moreSong = (Button) findViewById(R.id.moresong);
		if(!isCatalogue)
		{
			moreSong.setVisibility(View.GONE);
		}
		
		imv = (ImageView) findViewById(R.id.ImageView01);
		
		
			if(!fromCatalogue)
			{
				dl.setVisibility(Button.GONE);
				play.setVisibility(Button.GONE);
				statusBar.setVisibility(View.GONE);
				
				try {
					ds = createFromSongD(item);
				} catch (IOException e) {
					
					e.printStackTrace();
				}
				Bitmap pic = LoadImageFromWebOperations(ds.album, ds.albid);
				if(pic!=null)
				imv.setImageBitmap(pic);
				else 
					imv.setImageResource(R.drawable.header);
			}
			else
			{
				try {
					URL url = new URL("http://secure.musiklegal.com/?action=track&method=get_info&idring="+ds.idring+"&api_key="+mercapi);
					Log.e("tes", "http://secure.musiklegal.com/?action=track&method=get_info&idring="+ds.idring+"&api_key="+mercapi);
					url.openConnection();
					InputStream is = url.openStream();
					SAXParserFactory spf =SAXParserFactory.newInstance();
					InfoParser ip = new InfoParser();
					SAXParser sp = spf.newSAXParser();
					XMLReader xml = sp.getXMLReader();
					xml.setContentHandler(ip);
					xml.parse(new InputSource(is));
					is.close();
					ds = ip.anItem;
					//Log.e("tes",ds.album);
					Bitmap pic = LoadImageFromWebOperations(ds.album, ds.albid);	
					//Log.i("url","http://secure.musiklegal.com/?action=track&method=get_info&idring="+ds.idring+"&api_key="+mercapi);
					if(pic!=null)
					imv.setImageBitmap(pic);
					
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ParserConfigurationException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SAXException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		
		
		song = (TextView) findViewById(R.id.song);
		song.setText(  ds.song);
		artist = (TextView) findViewById(R.id.artist);
		artist.setText( ds.artist);
		album = (TextView) findViewById(R.id.album);
		album.setText( ds.alname);
		genre = (TextView) findViewById(R.id.genre);
		genre.setText( ds.genre);
		label = (TextView) findViewById(R.id.label);
		label.setText( ds.label);
		idring = (TextView) findViewById(R.id.idring);
		idring.setText( ds.idring);
		composer = (TextView) findViewById(R.id.comp);
		composer.setText( ds.composer);
		publisher = (TextView) findViewById(R.id.pub);
		publisher.setText( ds.pub);
		
		moreSong.setOnClickListener(new OnClickListener()
		{
			public void onClick(View v) 
			{
				new Thread(new Runnable(){

					public void run() {
						if(MusikLegal.internet(getApplicationContext()))
						{
							AnotherSong.artistId= ds.artist_id;
							if(mercapi!=null)
							AnotherSong.merchantKey= mercapi;
							else
								AnotherSong.merchantKey = ds.api;
							isCatalogue=false;
							donlot.post(new Runnable(){

							public void run() {
								startActivity(new Intent(getApplicationContext(),AnotherSong.class));
								
							}});
						
						}
						else
						{
							donlot.post(new Runnable(){

								public void run() {
									Toast.makeText(getApplicationContext(), Settings.gakonek, Toast.LENGTH_SHORT).show();
									
								}});
							
						}
							
						
					}}).start();
				
			}
		});
		
		if(fromCatalogue)
		{
			address = "http://preview.imortalnow.com/" + ds.idring + ".mp3";
			
			mediaPlayer = new MediaPlayer();
			//state=true;
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
	
				public void onPrepared(MediaPlayer mp) {
	
					Toast.makeText(TrackInfo.this, "Preview Ready",
							Toast.LENGTH_SHORT).show();
					state = true;
				}
			});
			
			mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
				
				public void onCompletion(MediaPlayer arg0) 
				{
					//play.setText("Preview");
					//state=true;
				}
			});
	
			try {
				mediaPlayer.setDataSource(address);
				mediaPlayer.prepareAsync(); // might take long! (for buffering, etc)
	
			} catch (IllegalArgumentException e2) 
			{
				e2.printStackTrace();
			} catch (IllegalStateException e2) {
				
				e2.printStackTrace();
			} catch (IOException e2) {
				
				e2.printStackTrace();
			}
	
			
			
			dl.setOnClickListener(new OnClickListener() {
				public void onClick(View arg0) {
					if(!isdownloading)
					{
						try {
							if(!fromFriend)
							url = new URL(
									"http://secure.musiklegal.com/?action=track&method=download&idring="
											+ ds.idring + "&api_key="
											+mercapi);
							else
								url = new URL(
										"http://secure.musiklegal.com/?action=track&method=download&idring="
												+ ds.idring + "&api_key="+mercapi
												);
							
							new Thread(new Runnable() {
		
								public void run() {
			
									donlot.post(new Runnable() {
		
										public void run() {
											isdownloading = true;
											
									statusBar.setVisibility(ProgressBar.VISIBLE);
									statusBar.setProgress(0);
										}});
									download(url);						
								}
							}).start();
						} catch (IOException e) {
		
							
						}
					}
					else
					{
						Toast.makeText(getApplicationContext(), "You are still downloading a song", Toast.LENGTH_SHORT).show();
					}
					System.gc();
				}
	
			});
	
			play.setOnClickListener(new OnClickListener() {
	
				public void onClick(View arg0) {
					if (state) {
						if (!mediaPlayer.isPlaying()) {
							if(MyD.isInited&&MyD.player.isPlaying())
							{
								MyD.player.pause();
								MyD.paused=true;
								delayed=true;
							}
							mediaPlayer.start();
							//play.setText("Preview");
						} else {
							mediaPlayer.pause();
							//play.setText("Preview");
						}
					} else {
						Toast.makeText(TrackInfo.this, "Preview is not Ready",
								Toast.LENGTH_SHORT).show();
					}
	
				}
			});
		}
		
		

	}
	
	boolean isdownloading=false;

	void download(URL url) {
		
		try {
			c = (HttpURLConnection) url.openConnection();
			c.setRequestMethod("GET");
			c.setDoOutput(true);
			c.connect();
			size= c.getContentLength();
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}

		String PATH = MusikLegal.mainFolder;
		file = new File(PATH);
		String fileName = ds.idring + ".g3n";

		File outputFile = new File(file, fileName);

		final SongD aSong = new SongD(ds.idring, ds.song, ds.artist, Calendar
				.getInstance().getTimeInMillis(), outputFile.getPath(),
				ds.albid,ds.genre,ds.composer,ds.pub,ds.artist_id);
		donlot.post(new Runnable(){

			public void run() {
				statusBar.setMax(size);
				
			}});
		
		 {

			
			BufferedOutputStream fos;
			try {
				fos = new BufferedOutputStream(new FileOutputStream(outputFile));
				InputStream is = c.getInputStream();
				stat=0;
				int len1 = 0;
				while ((len1 = is.read(MerchantAdapter.buffer)) != -1) 
				{
					stat += len1;
					fos.write(MerchantAdapter.buffer, 0, len1);
					
					donlot.post(new Runnable() {
						public void run() {
							statusBar.setProgress(stat);
						}
					});
				}

				fos.flush();
				fos.close();
				is.close();
				
				File albumart= new File(MusikLegal.albumArtFolder,aSong.albumid+".jpg");
				c = (HttpURLConnection) new URL(ds.album).openConnection();
				c.setRequestMethod("GET");
				c.connect();
				size = c.getContentLength();
				donlot.post(new Runnable(){

					public void run() {
						statusBar.setMax(size);
						statusBar.setProgress(0);
					}});
				is = c.getInputStream();
				
				BufferedInputStream bis = new BufferedInputStream(is);
				BufferedOutputStream bos = new BufferedOutputStream(
						new FileOutputStream(albumart));
				stat =0;
				byte[] buffer = new byte[1024];
				while ((len1=bis.read(buffer)) >= 0) {
					bos.write(buffer,0,len1);
					stat+=len1;
					donlot.post(new Runnable() {
						public void run() {
							statusBar.setProgress(stat);
						}
					});
				}

				bis.close();
				bos.flush();
				bos.close();
				
				

				
				if (MusikLegal.dataSet.add(aSong))
				{
					
					
					
				BufferedWriter bw = new BufferedWriter(new FileWriter(new File(
						MusikLegal.listD), true));
				bw.append(aSong.toString() + "\n");
				bw.flush();
				bw.close();
				MusikLegal.listDownload.add(aSong);
				donlot.post(new Runnable(){

					public void run() {
						Toast.makeText(getApplicationContext(), "Download Success ",
								Toast.LENGTH_SHORT).show();
						statusBar.setProgress(0);
						statusBar.setVisibility(View.INVISIBLE);
					}});
				}
				else
					{
						donlot.post(new Runnable(){

							public void run() {
								Toast.makeText(getApplicationContext(), "File Already Downloaded",
										Toast.LENGTH_SHORT).show();
								statusBar.setProgress(0);
								statusBar.setVisibility(View.INVISIBLE);
							}});
					}
				if(MusikLegal.db==null)
					{
						MusikLegal.db = new DataHelper(getApplicationContext());
					
					}
				
				if(!MusikLegal.db.isOpen())
					MusikLegal.db = new DataHelper(getApplicationContext());
				
				
				if(!MusikLegal.db.searchId(aSong.idRing))
					MusikLegal.db.insert(aSong.idRing, 3);
					
					
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				MusikLegal.dataSet.remove(aSong);
				MusikLegal.listDownload.remove(aSong);
				e.printStackTrace();
			}
			catch(IllegalStateException e)
			{
				MusikLegal.db = new DataHelper(getApplicationContext());
				if(!MusikLegal.db.searchId(aSong.idRing))
					MusikLegal.db.insert(aSong.idRing, 3);
			}
			
		} 
		 isdownloading=false;
		 

	}

	public void onDestroy() {
		super.onDestroy();
		isCatalogue = false;
		if(delayed)
		{
			MyD.player.start();
			MyD.paused=false;
		}
		
		if(fromCatalogue)
		{
			if(mediaPlayer!=null){
			mediaPlayer.stop();
			mediaPlayer.release();
			}
		}
		
		System.gc();
		
	}

	synchronized private Bitmap LoadImageFromWebOperations(String uRl, String alid) {
		File cache = new File(MusikLegal.albumArtFolder,"tempp");
		InputStream is = null;
		Bitmap bitmap;
		if(fromCatalogue){
			try {

				
				
				is = new URL(uRl).openConnection().getInputStream();
				 	OutputStream os = new FileOutputStream(cache);
		            Utils.CopyStream(is, os);
		            os.close();
		            bitmap = decodeFile(cache);
		            is.close();
		            if(bitmap!=null)
		            return Bitmap.createScaledBitmap(bitmap, pictsize, pictsize, false);
		            else return null;
				
			

			} 
			catch (MalformedURLException e) {
				Log.d("gambar","error "+e.getMessage() );
				e.printStackTrace();
			} catch (IOException e) {
				
				Log.d("gambar","error "+e.getMessage() );
				e.printStackTrace();
			}
			
		}
		else
		{
			File alb =  new File(MusikLegal.albumArtFolder,ds.albid+".jpg");
			Bitmap bitmp = decodeFile(alb);
			if(bitmp!=null)
			return Bitmap.createScaledBitmap(bitmp,pictsize,pictsize,false);
			else return null;
		}
		
			return null;

		} 
		
		
	
	
	static  Bitmap decodeFile(File f){
		 try {
	            //decode image size
	            BitmapFactory.Options o = new BitmapFactory.Options();
	            o.inJustDecodeBounds = true;
	            BitmapFactory.decodeStream(new FileInputStream(f),null,o);
	            //Find the correct scale value. It should be the power of 2
	            int scale=1;
	            //decode with inSampleSize
	            BitmapFactory.Options o2 = new BitmapFactory.Options();
	            o2.inSampleSize=scale;
	            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
	        } catch (FileNotFoundException e) {}
	        return null;
        
    }
	
	DataSong createFromSongD(SongD s) throws IOException
	{
		
		DataSong d = new DataSong();
		File f = new File(s.location);
		d.idring = s.idRing;
		d.song = s.title;
		d.artist = s.artist;
		byte[] meta = new byte[256];
		
		FileInputStream fis = new FileInputStream(f);
		
		fis.read(meta);
		
		StringBuffer data = new StringBuffer(new String(meta));
		d.alname =  data.substring(63,93).trim();
		d.genre = data.substring(107,127).trim();
		d.label = data.substring(199,229).trim();
		d.composer = s.composer;
		d.pub = s.pub;
		d.artist_id= s.artist_id;
		d.api = data.substring(177, 181).trim()+"-"+data.substring(181, 191).trim();
		d.album = URI.create(MusikLegal.albumArtFolder+s.albumid+".jpg").toString();
		d.albid = s.albumid;
		
		return d;
		
	}
}
